package com.congee02.sync;

import com.congee02.ThreadProvider;

/**
 * @author congee02
 * @date 2/2/2023 2:00 PM
 */
public class SynchronizedMethodSellTicketTest {
    
    private final static int NUM_OF_WINDOWS = 3;
    
    private static Thread[] generateWindows() {
        ThreadProvider provider = new SynchronizedMethodSellTicketThread();
        Thread[] windows = new Thread[NUM_OF_WINDOWS];
        for (int i = 0 ; i < windows.length ; i ++ ) {
            windows[i] = provider.thread("windows" + i);
        }
        return windows;
    }
    
    public static void main(String[] args) {
        Thread[] windows = generateWindows();
        for (Thread w : windows) {
            w.start();
        }
    }
    
    private static class SynchronizedMethodSellTicketThread implements ThreadProvider {

        private int ticketNum = 100;

        /**
         * 尝试售票，成功返回 true，失败返回 false
         */
        public synchronized boolean trySell() {
            
            if (ticketNum <= 0) {
                return false;
            }
            
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " 售出一张票，剩余票数: " + -- ticketNum);
            
            return true;
        }
        
        @Override
        public void run() {
            System.out.println(this);
            while (ticketNum > 0) {
              if (! trySell()) {
                  break;
              }
            }
            System.out.println(Thread.currentThread().getName() + " 售票结束");
        }
    }
}
